<template>
  <div class="home">
    <!-- 顶部导航栏 -->
    <van-nav-bar>
      <template #left>
        <van-image
          width="100"
          :src="require('../../assets/logo.png')"
          fit="contain"
      /></template>
      <template #right>
        <van-button @click="$router.push('/home/search')">
          <van-icon class="myicon" name="search" />
          搜索
        </van-button>
      </template>
    </van-nav-bar>

    <!-- 频道区域 -->
    <van-tabs v-model="active">
      <van-tab
        v-for="(item, index) in channelList"
        :key="index"
        :title="item.name"
      >
        <news-list :channel_id="item.id" />
      </van-tab>
      <van-icon @click="openChannel" class="channelIcon" name="wap-nav" />
    </van-tabs>

    <van-action-sheet v-model="channelShow" title="频道管理">
      <channel :channelList="channelList" v-model="active" />
    </van-action-sheet>
  </div>
</template>

<script>
import { getUserChannelAPI } from "@/api";
import { getChannel } from "@/utils/auth";
import newsList from "./components/newsList.vue";
import channel from "./components/channel.vue";
export default {
  components: {
    newsList,
    channel,
  },
  data() {
    return {
      channelList: [],
      channelShow: false,
      //  选中元素的下标
      active: 0,
    };
  },
  methods: {
    openChannel() {
      this.channelShow = true;
    },

    async getUserChannel() {
      const res = await getUserChannelAPI();
      this.channelList = res.data.data.channels;
    },
  },

  created() {
    // this.getUserChannel();
    const token = this.$store.state.token.token;
    // 代码优化
    const local = getChannel();
    if (token || !local) {
      this.getUserChannel();
    } else {
      this.channelList = local;
    }

    // if (token) {
    //   this.getUserChannel();
    // } else {
    //   const local = getChannel();
    //   if (local) {
    //     this.channelList = local;
    //   } else {
    //     this.getUserChannel();
    //   }
    // }
  },
};
</script>

<style lang="less">
.home {
  button.van-button.van-button--default.van-button--normal {
    background-color: #5aabfb;
    color: #fff;
    border: none;
    border-radius: 20px;
    height: 30px;
    padding: 0 20px;
  }
  .myicon {
    color: #fff !important;
    margin-right: 6px !important;
  }
  .channelIcon {
    position: absolute;
    top: 0;
    right: 0;
    font-size: 20px;
    height: 40px;
    line-height: 40px;
    width: 10%;
    text-align: center;
    background-color: #fff;
    // background-color: red;
  }
  .van-tabs__wrap.van-tabs__wrap--scrollable {
    width: 90%;
  }
}
</style>